import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import * as routerActions from 'react-router-redux';
import { generateUUID } from 'Utils/index';
import './index.scss';


class Tab extends React.PureComponent {
  static propType = {
    configTab: PropTypes.arrayOf(
      PropTypes.shape({
        label: PropTypes.string,
        route: PropTypes.string
      })
    ).isRequired,
  };
  constructor(props) {
    super(props);
    this.state = {
      selectTab: '',
    };
    this.checkSelected = ::this.checkSelected;
  }
  componentWillMount() {
    const { locationBeforeTransitions } = this.props;
    this.setState({
      selectTab: locationBeforeTransitions.pathname
    });
  }
  componentWillReceiveProps(nextProps) {
    const { locationBeforeTransitions } = nextProps;
    this.setState({
      selectTab: locationBeforeTransitions.pathname
    });
  }
  handleChangeTab(route) {
    this.setState({
      selectTab: route
    });
    this.props.dispatch(routerActions.replace(route));
  }
  checkSelected(tab) {
    const { selectTab } = this.state;
    const checkRoute = tab.route;
    if (selectTab === checkRoute) {
      return true;
    }
    if (tab.level) {
      const selectTabArr = selectTab.split('/');
      selectTabArr.shift();
      const CheckRouteArr = checkRoute.split('/');
      CheckRouteArr.shift();
      for (let i = 0; i < tab.level; i++) {
        if (selectTabArr[i] !== CheckRouteArr[i]) {
          return false;
        }
      }
      return true;
    }
    return false;
  }
  selestItem(checkSelect, index, len) {
    if (checkSelect && index === 1) {
      return 'menu-first-select';
    }
    if (checkSelect && index === len) {
      return 'menu-last-select';
    }
    return 'menu-normal-select';
  }
  renderTab() {
    const nodeInfo = [];
    const { configTab } = this.props;
    for (let i = 0, len = configTab.length; i < len; i++) {
      nodeInfo.push((
        <div
          key={generateUUID()}
          className={`${this.checkSelected(configTab[i]) ? 'tab-select' : ''} ${this.selestItem(this.checkSelected(configTab[i]), i + 1, len)}`}
          onClick={this.handleChangeTab.bind(this, configTab[i].route)}
        >
          {configTab[i].label}
        </div>
      ));
    }
    return nodeInfo;
  }
  render() {
    return (
      <div className="tab-wrap">
        {
          this.renderTab()
        }
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    ...state.routing
  };
}

export default connect(mapStateToProps)(Tab);
